package com.zja.servlet;


import com.zja.model.KnowledgeBase;
import com.zja.model.User;
import com.zja.service.Impl.KnowledgeBaseServiceImpl;
import com.zja.service.KnowledgeBaseService;
import com.zja.util.JsonUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.Timestamp;

/**
 * @author JA
 * @date: 2025/5/3
 * description:修改知识库信息
 */
@WebServlet("/api/knowledgebase/update")
public class UpdateKnowledgeBaseServlet extends HttpServlet {
    private final KnowledgeBaseService knowledgeBaseService = new KnowledgeBaseServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");

        HttpSession session = req.getSession(false);
        if (session == null || session.getAttribute("currentUser") == null) {
            resp.getWriter().write(JsonUtil.toJson(new Result(false, "请先登录")));
            return;
        }

        User currentUser = (User) session.getAttribute("currentUser");

        // 读取 JSON 请求体
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = req.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }

        KnowledgeBase input = JsonUtil.fromJson(sb.toString(), KnowledgeBase.class);

        KnowledgeBase existing = knowledgeBaseService.getById(input.getId());
        if (existing == null) {
            resp.getWriter().write(JsonUtil.toJson(new Result(false, "知识库不存在")));
            return;
        }

        if (!existing.getCreatorId().equals(currentUser.getId())) {
            resp.getWriter().write(JsonUtil.toJson(new Result(false, "无权限修改该知识库")));
            return;
        }

        // 更新信息
        existing.setName(input.getName());
        existing.setDescription(input.getDescription());
        existing.setAccessLevel(input.getAccessLevel());
        existing.setUpdatedAt(new Timestamp(System.currentTimeMillis()));

        boolean updated = knowledgeBaseService.update(existing);
        if (updated) {
            resp.getWriter().write(JsonUtil.toJson(new Result(true, "更新成功")));
        } else {
            resp.getWriter().write(JsonUtil.toJson(new Result(false, "更新失败")));
        }
    }

    static class Result {
        public boolean success;
        public String message;

        public Result(boolean success, String message) {
            this.success = success;
            this.message = message;
        }
    }
}
